package com.concurrent.schedule;

import com.concurrent.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.management.MalformedObjectNameException;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhangjiawen on 2019/8/13.
 */
//@Component
public class RedisSchedule {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String publicKey="CommonKey";
    Boolean lock=false;
    @Scheduled(cron="*/5 * * * * *")
    public void setNx() {
        System.out.println("TimeUnit.SECONDS"+TimeUnit.SECONDS);
        try {
            String ipConfig=IpUtil.getIp() + ":" + IpUtil.getPort();
            lock= redisTemplate.opsForValue().setIfAbsent(publicKey, ipConfig);
            if(!lock){
                String value=redisTemplate.opsForValue().get(publicKey);
                logger.warn("key have exist belong to:"+value);
            }else{
                redisTemplate.opsForValue().set(publicKey,ipConfig,60, TimeUnit.SECONDS);
                //获取锁成功
                logger.info("start lock lockNxExJob success");
                Thread.sleep(5000);
            }
        }catch (Exception e){
            logger.error("setNx error!");
            e.printStackTrace();
        }finally {
            redisTemplate.delete(publicKey);
        }

    }

}
